# -*- coding: utf-8 -*-
"""
http://www.suiszfpay.cn/
"""
import hashlib
import json
import random
import string
from collections import OrderedDict

import requests
import xmltodict
from dicttoxml import dicttoxml
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)
APP_CONF = {
    '16650': {
        'API_KEY': 'bc9df65e438a4d27899581a371cc9f4c',
        'gateway': 'http://api.suiszf.com/pay/gateway',
        'query_gateway': 'http://api.suiszf.com/pay/gateway',
    },
    '17306': {  # loki 限额1-5000
        'API_KEY': 'e13723e3027042b490ed7a7938402bda',
        'gateway': 'http://api.suiszf.com/pay/gateway',
        'query_gateway': 'http://api.suiszf.com/pay/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    parameter_dict = {
        'service': 'pay.alipay.wap',
        'mch_id': mch_id,
        'mch_no': str(pay.id),
        'total_fee': str(int(pay_amount * 100)),
        'notify_url': '{}/pay/api/{}/suiszfpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'success_url': '{}/pay/api/{}/suiszfpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'nonce_str': str(pay.id),
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("suiszfpay create: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(mch_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("suiszfpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# ok
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    _LOGGER.info("suiszfpay notify data : %s", data)
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['mch_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('suiszfpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay or pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['pay_state'])
    mch_id = pay.mch_id
    trade_no = data['sys_no']
    total_fee = data['total_fee']
    total_fee = float(total_fee) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 支付结果：1—成功；其它—失败
    if trade_status == 1:
        _LOGGER.info('suiszfpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('service', 'unified.trade.query'),
        ('mch_id', app_id),
        ('mch_no', str(pay_order.id)),
        ('nonce_str', ''.join(random.sample(string.ascii_letters + string.digits, 8))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    xml_data = dicttoxml(parameter_dict)
    _LOGGER.info("suiszfpay query create data: %s", parameter_dict)
    headers = {'Content-Type': 'application/xml'}
    response = requests.post(_get_query_gateway(app_id), data=xml_data, headers=headers, timeout=3).text
    _LOGGER.info("suiszfpay query data: %s", response)
    data = xmltodict.parse(response)['xml']
    result = int(data['pay_state'])
    order_id = data['sys_no']
    total_fee = float(data['total_fee']) / 100.0

    if result == 1:
        trade_no = order_id
        extend = {
            'trade_status': result,
            'trade_no': order_id,
            'total_fee': total_fee
        }
        _LOGGER.info('suiszfpay query order success, mch_id:%s pay_id:%s', pay_order.mch_id, pay_order.id)
        order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('suiszfpay query order fail, status_code: %s', result)
